from django.http import JsonResponse
from elasticsearch_dsl import Q
from pymongo import MongoClient
from django.conf import settings
from .sync_service import DataSyncService
from .models import TPADocument


class SearchView:
    def __init__(self):
        self.mongo_client = MongoClient(settings.MONGODB_URI)
        self.db = self.mongo_client[settings.MONGODB_DB]
        self.collection = self.db[settings.MONGODB_COLLECTION]

    def search(self, request):
        query = request.GET.get('q', '')

        # ES搜索
        search_query = Q('match', problem=query)
        es_results = TPADocument.search().query(search_query).execute()

        # 获取MongoDB详细数据
        mongo_ids = [result.mongo_id for result in es_results]
        from bson import ObjectId
        mongo_object_ids = [ObjectId(id) for id in mongo_ids]

        detailed_results = self.collection.find({
            '_id': {'$in': mongo_object_ids}
        })

        # 格式化结果
        results = []
        for doc in detailed_results:
            results.append({
                'id': str(doc['_id']),
                'problem': doc['problem'],
                # 添加其他需要的字段
            })

        return JsonResponse({
            'status': 'success',
            'data': results,
            'total': len(results)
        })